<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷" prop="paperId" style="width: 200px;">
        <el-select v-model="queryParams.paperId" placeholder="试卷" clearable>
          <el-option
              v-for="(item,index) in paperList"
              :key="index"
              :label="item.title"
              :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="题目类型" prop="questionType" style="width: 200px;">
        <el-select v-model="queryParams.questionType" placeholder="题目类型" clearable>
          <el-option
              v-for="dict in question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="因子维度" prop="symptomCluster" style="width: 200px;">
        <el-select v-model="queryParams.symptomCluster" placeholder="量表因子维度" clearable>
          <el-option
              v-for="dict in symptom_cluster_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否必答" prop="required" style="width: 200px;">
        <el-select v-model="queryParams.required" placeholder="是否必答" clearable>
          <el-option
              v-for="dict in exam_required"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['question:question:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['question:question:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['question:question:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['question:question:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="所属试题" align="center" prop="examPaper.title"/>
      <el-table-column label="量表因子维度类型" align="center" prop="symptomCluster">
        <template #default="scope">
          <dict-tag :options="symptom_cluster_type" :value="scope.row.symptomCluster"/>
        </template>
      </el-table-column>
      <!--<el-table-column label="题目内容" align="center" prop="content"/>-->
      <!--<el-table-column label="选项配置" align="center" prop="options"/>-->
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="是否必答" align="center" prop="required">
        <template #default="scope">
          <dict-tag :options="exam_required" :value="scope.row.required"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="修改人" align="center" prop="updateBy"/>
      <el-table-column label="修改时间" align="center" prop="updateTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleShow(scope.row)">查看
          </el-button>
          <el-button link type="primary" icon="EditPen" @click="handleUpdate(scope.row)"
                     v-hasPermi="['question:question:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['question:question:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改选项表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="80px" :disabled="disabledFlag">
        <el-form-item label="试题" prop="paperId">
          <el-select v-model="form.paperId" placeholder="请选择试题" clearable
                     style="width: 200px">
            <el-option
                v-for="(item,index) in paperList"
                :key="index"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型" prop="questionType">
          <el-radio-group v-model="form.questionType">
            <el-radio-button
                v-for="dict in question_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="量表因子维度" prop="symptomCluster">
          <el-radio-group v-model="form.symptomCluster">
            <el-radio-button
                v-for="dict in symptom_cluster_type"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题目内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <!-- 单独一行的添加按钮 -->
        <el-row>
          <el-col :span="12" :offset="9">
            <el-button type="success" @click="addOption()" v-show="!disabledFlag">
              添加选项
            </el-button>
          </el-col>
        </el-row>
        <el-form-item label="题目选项"> <!--prop="options"-->
          <div v-if="form.questionType === '0' || form.questionType === '1'">
            <el-row v-for="(option , index) in options" :key="index">
              <!--前缀-->
              <el-col :span="4">
                <el-tag type="info" v-model="option.key">{{ optionLabel(index) }}</el-tag>
              </el-col>
              <el-col :span="16">
                <el-select
                    v-model="option.score"
                    placeholder="选择选项"
                    clearable
                >
                  <el-option
                      v-for="dict in exam_options"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button icon="Delete" @click="removeOption(index)">删除</el-button>
              </el-col>
            </el-row>
          </div>
          <!-- 填空题输入 -->
          <!--<div v-if="form.questionType === '3'">
            <el-input v-model="fillBlanks" placeholder="请定义填空位置，用 {{blank}} 表示填空"></el-input>
          </div>-->
        </el-form-item>
        <el-form-item label="题目排序" prop="sort">
          <el-input-number controls-position="right" :min="0" v-model="form.sort" placeholder="请输入题目排序"/>
        </el-form-item>
        <el-form-item label="是否必答" prop="required">
          <el-radio-group v-model="form.required">
            <el-radio-button
                v-for="dict in exam_required"
                :key="dict.value"
                :value="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import {
  addQuestion,
  delQuestion,
  getAllPaper,
  getQuestion,
  listQuestion,
  updateQuestion
} from "@/api/question/question";
import {onMounted, nextTick} from "vue";

const {proxy} = getCurrentInstance();
const {
  question_type,
  exam_required,
  exam_options,
  symptom_cluster_type
} = proxy.useDict('question_type', 'exam_required', 'exam_options', 'symptom_cluster_type');

const questionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const paperList = ref([]);
const options = ref([]);
const disabledFlag = ref(false);// 禁用标识

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paperId: null,
    questionType: null,
    content: null,
    required: null
  },
  rules: {
    paperId: [
      {required: true, message: "试卷表id不能为空", trigger: "change"}
    ],
    questionType: [
      {required: true, message: "题目类型不能为空", trigger: "change"}
    ],
    symptomCluster: [
      {required: true, message: "量表因子维度不能为空", trigger: "change"}
    ],
    content: [
      {required: true, message: "题目内容不能为空", trigger: "blur"}
    ],
    options: [
      {required: true, message: "选项配置不能为空", trigger: "change"}
    ],
    sort: [
      {required: true, message: "题目排序不能为空", trigger: "blur"}
    ],
    required: [
      {required: true, message: "是否必答不能为空", trigger: "change"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);


// 选项标签生成（A、B、C...）
const optionLabel = (index) => {
  return String.fromCharCode(65 + index)
}

// 添加选项
const addOption = () => {
  if (!form.value.questionType || !form.value.symptomCluster) {
    proxy.$message.warning('请先选择题目类型和量表因子维度！');
  }
  // 当选择了题目类型时才可以添加选项
  if ((form.value.questionType === '0' || form.value.questionType === '1') && form.value.symptomCluster) {
    options.value.push({
      key: optionLabel(options.value.length),
      score: undefined
    });
  }
}
// 删除选项
const removeOption = (index) => {
  options.value.splice(index, 1);
}


/** 查询选项表列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    paperId: null,
    questionType: null,
    symptomCluster: null,
    content: null,
    options: [],
    sort: null,
    required: null
  };
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  disabledFlag.value = false;
  reset();
  // 点击新增按钮时将options清空
  options.value = [];
  open.value = true;
  title.value = "添加选项表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disabledFlag.value = false;
  reset();
  const _id = row.id || ids.value
  getQuestion(_id).then(response => {
    form.value = response.data;
    // 将回显的json格式的选项转换回去
    options.value = JSON.parse(response.data.options)
    open.value = true;
    title.value = "修改选项表";
  });
}

/** 查看按钮操作 */
function handleShow(row) {
  reset();
  const _id = row.id || ids.value
  getQuestion(_id).then(response => {
    console.log("response", response);
    form.value = response.data;
    // 将回显的json格式的选项转换回去
    options.value = JSON.parse(response.data.options)
    open.value = true;
    title.value = "查看选项表";
    disabledFlag.value = true;
  });
}


/** 提交按钮 */
function submitForm() {
  // 点击提交时，将值赋值给v-model绑定的输入框
  form.options = JSON.stringify(options.value.map(item => {
    return {
      key: item.key,
      score: item.score,
      // label:item.text,
    }
  }));
  let submitData = {
    id: form.value.id,
    paperId: form.value.paperId,
    questionType: form.value.questionType,
    symptomCluster: form.value.symptomCluster,
    content: form.value.content,
    options: form.options,
    sort: form.value.sort,
    required: form.value.required,
  }
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateQuestion(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选项表编号为"' + _ids + '"的数据项？').then(function () {
    return delQuestion(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('question/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
  // 弹框展开时，获取所有试卷
  if (open) {
    getAllPaper().then(response => {
      paperList.value = response.rows;
    })
  }
})
</script>


<style scoped>
/* 为选项添加间隔 */
.el-row {
  margin-bottom: 12px;
  padding: 8px;
  border-radius: 4px;
  background: #f8f9fa;
}

/* 错误状态提示 */
.el-select.is-error {
  border: 1px solid var(--el-color-danger);
}

el-select {
  width: 200px;
}
</style>





